package ncme.auto.framework.core.resolvers;

import ncme.auto.framework.core.entities.ResMsg;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sjh
 * Description https://blog.csdn.net/weixin_30480583/article/details/95301192
 * create 2021/11/24 10:26
 */
@Deprecated
public class AutoResultHandler implements HandlerMethodReturnValueHandler {

    private RequestResponseBodyMethodProcessor target;

    public AutoResultHandler() {
    }

    public AutoResultHandler(RequestResponseBodyMethodProcessor target) {
        this.target = target;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ncme.auto.framework.core.annotation.handler.AutoResultHandler.class) ||
                returnType.hasMethodAnnotation(ncme.auto.framework.core.annotation.handler.AutoResultHandler.class));
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        mavContainer.setRequestHandled(true);
        ncme.auto.framework.core.annotation.handler.AutoResultHandler methodAnnotation = methodParameter.getMethodAnnotation(ncme.auto.framework.core.annotation.handler.AutoResultHandler.class);
        if (methodAnnotation != null) {
            if (!(returnValue instanceof ResMsg)) {
                Map<String, Object> map = new HashMap<>();
                map.put("result", returnValue);
                returnValue = ResMsg.successRes(map);
            }
        }
        target.handleReturnValue(returnValue, methodParameter, mavContainer, webRequest);
    }

    public HttpServletResponse getServletResponse(NativeWebRequest webRequest) {
        return webRequest.getNativeResponse(HttpServletResponse.class);
    }

}
